<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<template>
  <div>
    <!-- 搜索 -->
    <el-form :model="formItem"  label-width="80px" :inline="true" class="demo-form-inline">
      <el-form-item label="活动名称">
        <el-input v-model="formItem.keyword" placeholder="活动名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="searchSubmit('formItem')">搜索</el-button>
      </el-form-item>
    </el-form>
    <!--<div style="margin-bottom: 10px;">
      <el-button @click="addActivity()" type="primary" size="mini">添加</el-button>
      <el-button @click.native="deleteAll()" type="danger" size="mini">删除</el-button>
    </div>-->
    <el-table ref="selection" :data="listData" border tooltip-effect="dark" style="width: 100%"  @cell-dblclick="tableEdit" @selection-change="select">
      <el-table-column fixed type="selection" width="55"></el-table-column>
     <!-- <el-table-column prop="avatar" label="活动图片">
        &lt;!&ndash; 图片的显示 &ndash;&gt;
        <template  slot-scope="scope">
          <div class="demo-image__preview">
            <el-image :src="scope.row.file.path" :preview-src-list="getImgList(scope.row)" style="width:50px;height:50px;borderRadius: 25px;"></el-image>
          </div>
        </template>
      </el-table-column>-->
      <el-table-column prop="name" label="活动名称" width="200"></el-table-column>
      <el-table-column prop="goods_num" label="商品数量" width="200"></el-table-column>
      <el-table-column prop="describe" label="报名规则" show-overflow-tooltip width="300">
        <template slot-scope="scope">
          <div v-html="scope.row.describe"></div>
        </template>
      </el-table-column>
      <!--<el-table-column prop="help_num" label="助力人数" width="200"></el-table-column>-->
      <el-table-column prop="start_time" label="开始时间" width="200"></el-table-column>
      <el-table-column prop="end_time" label="结束时间" width="200"></el-table-column>
      <!-- <el-table-column prop="get_time" label="截止时间" width="200"></el-table-column>-->
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status"
                     active-color="#00A854"
                     active-text="显示"
                     :active-value="1"
                     class="demo"
                     inactive-color="#F04134"
                     inactive-text="隐藏"
                     :inactive-value="2"
                     @change="changeSwitch(scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="200">
        <template slot-scope="scope">{{ scope.row.sort }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="320">
        <template slot-scope="scope">
          <el-button @click.native.prevent="goods(scope.$index)" type="primary" size="mini">奖品</el-button>
          <el-button @click.native.prevent="edit(scope.$index)" type="primary" size="mini">编辑</el-button>
          <!--<el-button @click.native.prevent="del(scope.$index)" type="danger" size="mini">删除</el-button>-->
          <el-button @click.native.prevent="awardHistory(scope.$index)" type="primary" size="mini">中奖记录</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="text-align : right; float : right; margin-top: 10px;">
      <!--<span class="demonstration">完整功能</span>-->
      <el-pagination
              @size-change="handlePageSize"
              @current-change="handlePage"
              :current-page="pageNum"
              :page-sizes="[10, 50, 100, 200]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageTotal">
      </el-pagination>
    </div>
    <!-- 活动添加修改 -->
    <el-dialog :visible.sync="activityModal" :title="titleStr" width="75%">
      <el-form ref="activity" :model="formAdd" :rules="formAddValidate" label-width="80px" class="demo-ruleForm">
        <el-form-item  label="商品数量" prop="goods_num">
          <el-input-number v-model="formAdd.goods_num" :min="1" :max="10000" style="width:300px;"></el-input-number>
          <span>转盘的奖品数量</span>
        </el-form-item>
        <!--<el-form-item label="活动图片" prop="img">
          <el-upload
                  ref="upload"
                  class="avatar-uploader"
                  :action="fileUpload"
                  :show-file-list="false"
                  :on-success="handleSuccess"
                  :before-upload="beforeAvatarUpload">
            <img v-if="imgUrl" :src="imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>-->
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="formAdd.name" style="width:300px;"  placeholder="请输入活动名称"></el-input>
        </el-form-item>
        <el-form-item label="分享标题" prop="share_title">
          <el-input v-model="formAdd.share_title" style="width:300px;"  placeholder="请输入分享标题"></el-input>
        </el-form-item>
        <el-form-item label="报名规则" prop="describe">
          <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="formAdd.describe"></el-input>
        </el-form-item>
        <el-form-item label="开始时间" prop="start_time">
          <el-date-picker v-model="formAdd.start_time" type="datetime" placeholder="选择日期时间" style="width:300px;"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="end_time">
          <el-date-picker v-model="formAdd.end_time" type="datetime" placeholder="选择日期时间" style="width:300px;"></el-date-picker>
        </el-form-item>
        <!--<el-form-item label="领取时间" prop="get_time">
          <el-date-picker v-model="formAdd.get_time" type="datetime" placeholder="选择领取时间" style="width:300px;"></el-date-picker>
          <span>领取奖品的截止时间</span>
        </el-form-item>
        <el-form-item label="助力人数" prop="help_num">
          <el-input-number v-model="formAdd.help_num" :min="0" :max="10000" style="width:300px;"></el-input-number>
        </el-form-item>-->
        <el-form-item label="抽奖规则" prop="rules">
          <el-input type="textarea" :rows="6" placeholder="请输入内容" v-model="formAdd.rules"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formAdd.sort" :min="1" :max="10000" style="width:300px;"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click.native="activitySubmit('formAdd')">提交</el-button>
          <el-button @click="activityCancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import axios from "@/axios";
import EditorText from "@/components/EditorText.vue"
import { isIntNum,getHeaders } from "@/assets/js/common";
import moment from 'moment'
export default {
  data() {
    return {
      activityModal: false,
      imgUrl: "",
      formItem: {
        keyword: "",
      },
      titleStr: '',
      formAdd: {
        name: "",
        share_title:"",
        describe: "",
        rules: "",
        start_time: "",
        end_time: "",
        goods_num: 1,
        sort: 1
      },
      formAddValidate: {
        name: [
          {
            required: true,
            message: "活动名称不能为空",
            trigger: "change"
          }
        ],
        share_title: [
          {
            required: true,
            message: "分享标题不能为空",
            trigger: "change"
          }
        ],
        start_time:[
          {
            required: true,
            message: "开始时间不能为空",
            trigger: "change"
          }
        ],
        end_time:[
          {
            required: true,
            message: "结束时间不能为空",
            trigger: "change"
          }
        ],
        describe: [
          {
            required: true,
            message: "报名规则不能为空",
            trigger: "change"
          }
        ]
      },
      ids: [],
      listData: [],
      pageTotal: 0,
      pageNum: 1,
      pageSize: 10,
      headers: {},
      credentials: true,
      fileUpload: "",
    };
  },
  //注册组件
  components: {
    EditorText,
  },
  mounted() {
    this.base = JSON.parse(sessionStorage.base);
    this.fileUpload = this.base.domain_name + "/api/file/upload";
    this.headers = getHeaders(localStorage._token);
    // 活动列表
    this.getActivity();
  },
  methods: {
    tableEdit(row, column, cell, event) {
      let vm = this;
      if (column.label) {
        // 获取当前的值
        var beforeVal = event.target.textContent;
        event.target.innerHTML = "";
        let str = `<div class='cell'>
            <div class='el-input'>
              <input type='text' placeholder='请输入内容' class='el-input__inner'>
            </div>
        </div>`;
        cell.innerHTML = str;
        // 获取双击后生成的input  根据层级嵌套会有所变化
        let cellInput = cell.children[0].children[0].children[0];
        cellInput.value = beforeVal;
        cellInput.focus(); // input自动聚焦
        // 失去焦点后  将input移除
        cellInput.onblur = function() {
          let onblurCont = `<div class='cell'>${cellInput.value}</div>`;
          cell.innerHTML = onblurCont; // 换成原有的显示内容
          // 调用axios接口
          if (column.property === 'sort'){
            axios
              .post("/admin/activity/updateSort", {
                id: row.id,
                sort: cellInput.value
              })
              .then(response => {
                let status = response.status;
                let data = response.data;
                if (data.code === 200) {
                  vm.$message({
                    type: 'success',
                    message: "操作成功!",
                    onClose: function (msg) {
                      vm.getActivity();
                    }
                  });
                } else {
                  vm.$message.info(data.message);
                }
              })
              .catch(error => {
                // vm.$Message.info("网络或服务器异常");
              });
          }
        };
      }
    },
    // 图片预览
    getImgList(row){
      let images = [];
      if (row.file) {
        images.push(row.file.path);
      }
      return images
    },
    //获取勾选参数
    select(val) {
      let vm = this;
      vm.ids = [];
      for (let i in val) {
        vm.ids.push(val[i].id);
      }
    },
    //当前页数
    handlePage(value) {
      this.pageNum = value;
      this.getActivity();
    },
    //每页显示条数
    handlePageSize(value) {
      this.pageSize = value;
      this.getActivity();
    },
    //获取活动列表
    getActivity() {
      let vm = this;
      axios
        .post("/admin/activity/getLists", {
          page: this.pageNum,
          limit: this.pageSize,
          keyword: this.formItem.keyword
        })
        .then(response => {
          let status = response.status;
          let data = response.data;
          if (data.code == 200) {
            let result = data.data;
            vm.pageTotal = result.total;
            vm.listData = result.list;
          } else {
            vm.$message.info(data.message);
          }
        })
        .catch(error => {
          // vm.$Message.info("网络或服务器异常");
        });
    },
    //更改状态
    changeSwitch(index) {
      let vm = this;
      if (this.listData[index].status == 1) {
        status = 2;
      } else {
        status = 1;
      }
      axios
        .post("/admin/activity/updateStatus", {
          id: vm.listData[index].id,
          status: status
        })
        .then(response => {
          let status = response.status;
          let data = response.data;
          if (data.code == 200) {
            this.$message({
              message: '操作成功!',
              type: 'success',
              onClose: function(msg) {
                vm.getActivity();
              }
            });
          } else {
            vm.$message.error(data.message);
          }
        })
        .catch(error => {
          // vm.$message.info("网络或服务器异常");
        });
    },
    //删除
    del: function (index = "") {
      let vm = this;
      //判断单条多条操作
      vm.ids = [];
      if (!isIntNum(index)) {
        vm.ids.push(vm.listData[index].id);
      } else {
        if (vm.ids.length < 1) {
          vm.$message.error("请勾选数据！");
          return false;
        }
      }
      this.$confirm("是否确认删除吗？", "确认删除" , {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios
          .post("/admin/activity/delete", {
            ids: vm.ids
          })
          .then(response => {
            let status = response.status;
            let data = response.data;
            if (data.code == 200) {
              vm.$message({
                type: 'success',
                message: "操作成功!",
                onClose: function (msg) {
                  vm.getAdmin();
                  vm.ids = [];
                }
              });
            } else {
              vm.$message.error(data.message);
            }
          })
          .catch(error => {
            //vm.$Message.info("网络或服务器异常");
          });
      }).catch(() => {
        vm.ids = [];
        this.$refs.selection.selectAll(false);
      });
    },
    // 添加
    addActivity() {
      this.titleStr = '添加';
      this.activityModal = true;
    },
    // 活动添加、编辑处理
    activitySubmit(name) {
      let vm = this;
      vm.formAdd.start_time = vm.formAdd.start_time ? moment(this.formAdd.start_time).format('YYYY-MM-DD HH:mm:ss') : "";
      vm.formAdd.end_time = vm.formAdd.end_time ? moment(this.formAdd.end_time).format('YYYY-MM-DD HH:mm:ss') : "";
      vm.formAdd.get_time = vm.formAdd.get_time ? moment(this.formAdd.get_time).format('YYYY-MM-DD HH:mm:ss') : "";
      this.$refs.activity.validate(valid => {
        if (valid) {
          axios
            .post("/admin/activity/store", vm.formAdd)
            .then(response => {
              let status = response.status;
              let data = response.data;
              if (data.code == 200) {
                vm.activityModal = false;
                vm.formAdd.id = "";
                vm.imgUrl = "";
                vm.formAdd.name = "";
                vm.formAdd.share_title = "";
                vm.formAdd.describe = "";
                vm.formAdd.goods_num = 1;
                vm.formAdd.rules = "";
                vm.formAdd.start_time = "";
                vm.formAdd.end_time = "";
                vm.formAdd.get_time = "";
                vm.formAdd.sort = 1;
                vm.$message({
                  type: 'success',
                  message: "操作成功!",
                  onClose: function (msg) {
                    vm.getActivity();
                  }
                });
              } else {
                vm.$message.error(data.message);
              }
            })
            .catch(error => {
              // console.log(error);
              // vm.$message.error("网络或服务器异常");
            });
        } else {
          // vm.$message.error("Fail!");
        }
      });
    },
    // 编辑
    edit(index) {
      this.titleStr = '编辑';
      this.activityModal = true;
      this.imgUrl = this.listData[index].file ? this.listData[index].file.path : '';
      this.formAdd = this.listData[index];
    },
    // 弹窗取消
    activityCancel() {
      this.activityModal = false;
      this.imgUrl = '';
      this.formAdd.id = "";
      this.formAdd.name = "";
      this.formAdd.share_title = "";
      this.formAdd.goods_num = 1;
      this.formAdd.describe = "";
      this.formAdd.rules = "";
      this.formAdd.start_time = "";
      this.formAdd.end_time = "";
      this.formAdd.get_time = "";
      this.formAdd.sort = 1;
      this.getActivity();
    },
    // 奖品
    goods(index) {
      this.$router.push({
        path: "activity_goods?activity_id="+this.listData[index].id
      });
    },
    // 中奖记录
    awardHistory(index) {
      this.$router.push({
        path: "award_history?activity_id="+this.listData[index].id
      });
    },
    //搜索
    searchSubmit() {
      this.pageNum = 1;
      this.getActivity();
    },
    // 批量删除
    deleteAll() {
      let vm = this;
      if (vm.ids.length < 1) {
        vm.$message.error("请勾选数据！");
        return false;
      }
      this.$confirm("是否确认删除吗？", "确认删除" , {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios
          .post("/admin/activity/delete", {
            ids: vm.ids
          })
          .then(response => {
            let status = response.status;
            let data = response.data;
            if (data.code == 200) {
              vm.$message({
                type: 'success',
                message: "操作成功!",
                onClose: function (msg) {
                  vm.getActivity();
                  vm.ids = [];
                }
              });
            } else {
              vm.$message.error(data.message);
            }
          })
          .catch(error => {
            //vm.$Message.info("网络或服务器异常");
          });
      }).catch(() => {
        vm.ids = [];
        this.$refs.selection.selectAll(false);
      });
    },
    // 图片上传
    handleSuccess(res, file) {
      let vm = this;
      if (res.code == 200) {
        this.imgUrl = res.img_path;
        this.formAdd.image = res.file;
      } else {
        vm.$message.error(res.message);
      }
    }
  }
};
</script>